<?php

namespace App\Models\Workflow;

use App\Enums\Workflow\WorkflowEnum;
use App\Models\BaseModel;
use App\Models\Traits\KfSoftDeletes;
use App\Models\Traits\KfUid;
use App\Service\OpenShop\User\RmsUserService;
use Illuminate\Database\Eloquent\Relations\HasOne;

class WorkflowOrderLogModel extends BaseModel
{
    use KfUid;
    use KfSoftDeletes;

    protected $table = 'workflow_order_logs';

    protected $fillable = [
        'workflowOrderId',
        'workflowOrderNodeId',
        'nodeName',
        'handlerUid',
        'handlerName',
        'audit',
        'content',
        'imgFiles',
        'rejectNodeId',
        'status',
        'isDeleted'
    ];

    const STATUS_WAIT   = 0;
    const STATUS_FINISH = 1;
    const STATUS_REJECT = 2;
    const STATUS_TEXT   = [
        self::STATUS_WAIT   => '待完成',
        self::STATUS_FINISH => '已完成',
        self::STATUS_REJECT => '已驳回',
    ];

    const AUDIT_DEFAULT = 0;
    const AUDIT_YES     = 1;
    const AUDIT_NO      = 2;
    const AUDIT_TEXT    = [
        self::AUDIT_DEFAULT => '',
        self::AUDIT_YES     => '通过',
        self::AUDIT_NO      => '驳回',
    ];

    public function workflowOrderNodeRel(): HasOne
    {
        return $this->hasOne(WorkflowOrderNodeModel::class, 'id', 'workflowOrderNodeId');
    }

    /**
     * 创建待处理节点日志
     * @param int $workflowOrderId
     * @param int $workflowOrderNodeId
     */
    public function add(int $workflowOrderId, int $workflowOrderNodeId)
    {
        $nodeModel = WorkflowOrderNodeModel::query()->where('id', $workflowOrderNodeId)->first();
        if (!$nodeModel) {
            return null;
        }

        $handlerName = RmsUserService::getRmsUserInfoByUserIds([$nodeModel->handlerUid], [],
            true)['data'][0]['username'] ?? '';
//
//        switch ($nodeModel->handlerType) {
//            case WorkflowEnum::HANDLER_TYPE_MERCHANT:
//
//                // 加盟商名称
//                $handlerName = RmsUserService::getRmsUserInfoByUserIds([$nodeModel->handlerUid], [],
//                    true)['data'][0]['username'] ?? '';
//                break;
//
//            default:
//                $handlerName = WorkflowEnum::HANDLER_TYPE_TEXT[$nodeModel->handlerType] ?? '-';
//        }

        return self::query()
                   ->create([
                       'workflowOrderId'     => $workflowOrderId,
                       'workflowOrderNodeId' => $workflowOrderNodeId,
                       'nodeName'            => $nodeModel->name,
                       'handlerUid'          => $nodeModel->handlerUid,
                       'handlerName'         => $handlerName,
                       'audit'               => self::AUDIT_DEFAULT,
                       'rejectNodeId'        => 0,
                       'status'              => self::STATUS_WAIT,
                   ]);
    }

    /**
     * 完成节点并生成下一个待处理节点
     * @param int $workflowOrderId
     * @param int $workflowOrderNodeId
     * @return void
     */
    public function finish(
        int $workflowOrderId,
        int $currentNodeId,
        int $dealUid,
        int $nextNodeId,
        int $audit,
        string $content,
        int $rejectNodeId
    ): void {

        if ($audit == self::AUDIT_NO) {
            $status = self::STATUS_REJECT;
        } else {
            $status = self::STATUS_FINISH;
        }

        $currentLog = self::query()
            ->where('workflowOrderId', $workflowOrderId)
            ->where('workflowOrderNodeId', $currentNodeId)
            ->orderByDesc('id')
            ->first();

        // 更新特殊日志的处理人
        if ($dealUid && $currentLog->handlerUid != $dealUid) {
            $currentLog->handlerUid  = $dealUid;
            $currentLog->handlerName = RmsUserService::getRmsUserInfoByUserIds([$dealUid], [],
                true)['data'][0]['username'] ?? '';
        }

        $currentLog->status       = $status;
        $currentLog->audit        = $audit;
        $currentLog->content      = $content;
        $currentLog->rejectNodeId = $rejectNodeId;
        $currentLog->save();

        if ($audit == self::AUDIT_NO) {

            // 驳回 - 跳转到指定节点
            $this->add($workflowOrderId, $rejectNodeId);
            return;
        }

        // 获取下个节点
        if ($nextNodeId <= 0) {
            return;
        }

        $nextNode = WorkflowOrderNodeModel::query()->where('id', $nextNodeId)->first();

        // 简单节点
        if ($nextNode->nodeType == WorkflowEnum::NODE_TYPE_SEQUENCE) {
            $this->add($workflowOrderId, $nextNodeId);
            return;
        }

        // 复杂节点
        WorkflowOrderNodeModel::query()
                              ->where('pId', $nextNodeId)
                              ->get()
                              ->each(function ($item) use ($workflowOrderId) {
                                  $this->add($workflowOrderId, $item->id);
                              });
    }

    /**
     * 商家看到的审批日志
     * @param int $workflowOrderId
     */
    public function merchantLogs(int $workflowOrderId)
    {
        $lists = self::query()
                     ->with('workflowOrderNodeRel')
                     ->where('workflowOrderId', $workflowOrderId)
                     ->get()
                     ->map(function (self $item) {
                         $nodeName    = $item->nodeName;
                         $handlerName = $item->handlerName;

                         if ($item->workflowOrderNodeRel->businessType == WorkflowEnum::BUSINESS_TYPE_FIX_AUDIT) {
                             if ($item->workflowOrderNodeRel->handlerType == WorkflowEnum::HANDLER_TYPE_SUPERVISE || $item->workflowOrderNodeRel->handlerType == WorkflowEnum::HANDLER_TYPE_PROVINCE) {
                                 $nodeName    = '续签初审';
                                 $handlerName = '省区分公司';
                             }

                             if ($item->workflowOrderNodeRel->handlerType == WorkflowEnum::HANDLER_TYPE_HEAD) {
                                 $nodeName    = '续签复审';
                                 $handlerName = '夸父总部';
                             }
                         } elseif ($item->workflowOrderNodeRel->businessType == WorkflowEnum::BUSINESS_TYPE_SUBMIT_APPLY) {
                             $handlerName = '加盟商';
                         }

                         return [
                             'nodeName'    => $nodeName,
                             'handlerName' => $handlerName,
                             'status'      => $item->status,
                             'statusText'  => self::STATUS_TEXT[$item->status] ?? '-',
                             'createdAt'   => $item->createdAt->toDateTimeString(),
                         ];
                     })->toArray();

        // 两个相邻的节点，如果nodeName一致，就删除先的那个
        $lists = array_reverse($lists);

        $lastNodeName = '';
        foreach ($lists as $k => $val) {
            if ($val['nodeName'] == $lastNodeName) {
                unset($lists[$k]);
            }

            $lastNodeName = $val['nodeName'];
        }

        return array_values(array_reverse($lists));
    }

    /**
     * 内部人看到的审批日志
     * @param int $workflowOrderId
     */
    public function kfLogs(int $workflowOrderId)
    {
        return self::query()
                   ->where('workflowOrderId', $workflowOrderId)
                   ->get()
                   ->map(function (self $item) {
                       return [
                           'nodeName'    => $item->nodeName,
                           'handlerName' => $item->handlerName,
                           'status'      => $item->status,
                           'statusText'  => self::STATUS_TEXT[$item->status] ?? '-',
                           'createdAt'   => $item->createdAt->toDateTimeString(),
                           'content'     => $item->content,
                       ];
                   });
    }
}
